<?php
namespace Sdk\Configuration\Adapter\CustomList;

use Marmot\Interfaces\INull;
use Marmot\Interfaces\IRestfulTranslator;
use Sdk\Common\Adapter\CommonRestfulAdapter;

use Sdk\Common\Adapter\Traits\MapErrorsTrait;
use Sdk\Common\Adapter\Traits\FetchAbleRestfulAdapterTrait;

use Sdk\Configuration\Model\CustomList;
use Sdk\Configuration\Model\NullCustomList;
use Sdk\Configuration\Translator\CustomListRestfulTranslator;

class CustomListRestfulAdapter extends CommonRestfulAdapter implements ICustomListAdapter
{
    use FetchAbleRestfulAdapterTrait,
        MapErrorsTrait;

    const MAP_ERROR = array(
        100001 => array(
            'category' => CUSTOMLIST_CATEGORY_FORMAT_INCORRECT,//category格式不正确
            'identify' => CUSTOMLIST_IDENTIFY_FORMAT_INCORRECT,//identify格式不正确
        ),
        100200 => array(
            'content' => CUSTOMLIST_CONTENT_FORMAT_INCORRECT,//content数据不正确
        ),
        100004 => array(
            'staff' => USER_IDENTITY_AUTHENTICATION_FAILED,//后台用户不存在|404
        )
    );
    
    const SCENARIOS = [
        'CUSTOMLIST_LIST'=>[
            'fields'=>[],
            'include' => ''
        ],
        'CUSTOMLIST_FETCH_ONE'=>[
            'fields'=>[],
            'include'=>''
        ]
    ];

    public function __construct(string $baseurl = '', array $headers = [])
    {
        parent::__construct(
            new CustomListRestfulTranslator(),
            'config/staff',
            $baseurl,
            $headers
        );
    }

    protected function getNullObject() : INull
    {
        return NullCustomList::getInstance();
    }

    protected function getAlonePossessMapErrors() : array
    {
        return self::MAP_ERROR;
    }

    public function scenario($scenario) : void
    {
        $this->scenario = isset(self::SCENARIOS[$scenario]) ? self::SCENARIOS[$scenario] : array();
    }

    public function save(CustomList $customList) : bool
    {
        $keys = array(
            'category',
            'identify',
            'content',
            'staff'
        );
        $data = $this->getTranslator()->objectToArray($customList, $keys);
        
        $this->patch(
            $this->getResource(),
            $data
        );
        
        if ($this->isSuccess()) {
            $this->translateToObject($customList);
            return true;
        }

        return false;
    }
}
